/*
 * Created on 2005-4-6
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.vandagroup.portal.menu.treeview;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;

import javax.servlet.jsp.JspWriter;

import com.vandagroup.common.util.SQLFormat;

/**
 * @author Administrator
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class FuncTreeView {
	private String[][] roleID = null;

	private String orgID = null;

	private String rootNO = "$$$$$$$$";

	StringBuffer html = null;

	public FuncTreeView(String[][] roleID, String orgID, String rootNO) {
		this.roleID = roleID;
		this.orgID = orgID;
		this.rootNO = rootNO;
	}

	public void create() throws Exception {
		String inClause = com.vandagroup.portal.PortalApp.getPaentFuncID(
				roleID, orgID);
		Statement stmt = null;
		ResultSet rs = null;
		TreeConnection treeConn = new TreeConnection();

		String[] roleIDs = new String[roleID.length];
		for (int i = 0; i < roleID.length; i++) {
			roleIDs[i] = roleID[i][0];
		}

		boolean canShow = false;
		if (rootNO.equals("$$$$$$$$"))
			canShow = true;
		try {
			/*
			 * String sql="WITH RPL ( PARENTFUNCID, FUNCID, FUNCDESC, URL ) AS ( "+
			 * "SELECT ROOT.PARENTFUNCID, ROOT.FUNCID, ROOT.FUNCDESC, ROOT.URL "+
			 * "FROM FUNC ROOT WHERE ROOT.PARENTFUNCID = '$$$$$$$$' UNION ALL
			 * SELECT CHILD.PARENTFUNCID, CHILD.FUNCID, CHILD.FUNCDESC,
			 * CHILD.URL FROM RPL PARENT, FUNC CHILD WHERE PARENT.FUNCID =
			 * CHILD.PARENTFUNCID ) SELECT DISTINCT PARENTFUNCID, FUNCID,
			 * FUNCDESC, URL FROM RPL WHERE RPL.FUNCID IN (" +"SELECT FUNCID
			 * FROM FUNC WHERE LEVELID IN ( "+inClause+")) ORDER BY
			 * PARENTFUNCID, FUNCID, FUNCDESC" ;
			 */
			String sql = "select  PARENTFUNCID,  FUNCID,  FUNCDESC,  URL from func where not funcid in (select parentfuncid from func)";
			sql += " and funcid in(select funcID from orgRoleFunc where orgID='"
					+ orgID
					+ "' and roleID in ("
					+ SQLFormat.joinAsList(roleIDs, true) + ")) ORDER BY PARENTFUNCID, FUNCID, FUNCDESC";

			treeConn.begin();
			stmt = treeConn.getConn().createStatement();
			rs = stmt.executeQuery(sql);

			html = new StringBuffer();
			html.append("<script language='javascript'>\n");
			html.append("<!--\n");
			html.append("var _arrTreeView = new Array();\n");
            TreeNode tmp=null;
			while (rs.next()) {
				if (rs.getString(2).equals(this.rootNO))
					canShow = true;
				if(funcTree.contains(rs.getString(2)))
					continue;
				this.funcTree.add(rs.getString(2));
				tmp=genFuncPath(treeConn.getConn(), rs.getString(1));
				if(tmp!=null)
				    html.append(tmp.getContent());
				
				html.append("_arrTreeView[ _arrTreeView.length ] = new Array(");
				html.append("\"" + rs.getString(1) + "\",");
				html.append("\"" + rs.getString(2) + "\",");				
				html.append("\"" + rs.getString(3) + "\",");
				if (rs.getString(4) != null) {
					html.append("\".." + rs.getString(4).trim() + "&_funcID="
							+ rs.getString(2) + "\"");
				} else {
					html.append("\"\"");
				}
				html.append(");\n");
				
			}
			rs.close();

			if (canShow) {

				sql = "select A.subjectNO,B.reportNO,B.name from reportFile A,reportInfo B where A.fileNO=B.fileNO and not A.subjectNO is null";

				sql += " and reportNO in(select reportNO from orgRoleReport where orgID='"
						+ orgID
						+ "' and roleID in ("
						+ SQLFormat.joinAsList(roleIDs, true) + "))";
				stmt = treeConn.getConn().createStatement();
				rs = stmt.executeQuery(sql);
				while (rs.next()) {
					html.append(this.genSubject(treeConn.getConn(), rs
							.getString(1)));
					html
							.append("_arrTreeView[ _arrTreeView.length ] = new Array(");

					html.append("\"S" + rs.getString(1) + "\",");
					html.append("\"B" + rs.getString(2) + "\",");
					html.append("\"[" + rs.getString(3) + "]\",");
					html
							.append("\"../Reportinfo.do?task=viewReport&step=init&reportno="
									+ rs.getString(2) + "\"");
					html.append(");\n");
				}
			}
			html
					.append("var treeView = new TreeView(\"$$$$$$$$\", \"功能列表\");\n");

			html.append("-->\n");
			html.append("</script>");
		} catch (Exception e) {
             e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
			} catch (Throwable e) {
				System.out.println("TreeView rs close error");
				e.printStackTrace();
			}

			try {
				if (stmt != null) {
					stmt.close();
				}
			} catch (Throwable e) {
				System.out.println("TreeView stmt close error");
				e.printStackTrace();
			}

			try {
				treeConn.free();
			} catch (Throwable e) {
				System.out.println("TreeView conn close error");
				e.printStackTrace();
			}
		}
	}

	/**
	 * 顯示功能表
	 * 
	 * @param out
	 *            Create Date : 2004-1-17
	 */
	public void display(JspWriter out) throws Exception {
		out.println(this.html.toString());
	}

	private static HashMap treePath = new HashMap();

	private HashSet funcTree = new HashSet();

	public TreeNode genFuncPath(Connection conn, String funcID) throws Exception {
		if(funcID.equals("$$$$$$$$")) return null;
		String t=funcID;
		TreeNode tn=null;
		if (funcTree.contains(funcID))
			return null;
		if (treePath.get(funcID) != null) {
			tn=(TreeNode) treePath.get(funcID);
			for(int i=0;i<tn.getNodes().size();i++){
				funcTree.add(tn.getNodes().get(i));
				System.out.print(tn.getNodes().get(i));
			}
			System.out.println();
			return (TreeNode)treePath.get(funcID);
		}
		tn=new TreeNode();
		funcTree.add(funcID);
		String sumHtml = "";
		Statement stmt = null;
		String topNO = null;
		String sql = null;
		while (!funcID.equals("$$$$$$$$")) {
			stmt = conn.createStatement();
			sql = "select PARENTFUNCID, FUNCID, FUNCDESC, URL from func where funcID='"
					+ funcID + "'";
			ResultSet rs = stmt.executeQuery(sql);
			if (!rs.next())
				return null;
			topNO = rs.getString(1);
			String html = "_arrTreeView[ _arrTreeView.length ] = new Array(";
			html += "\"" + topNO + "\",";
			html += "\"" + rs.getString(2) + "\",";
			html += "\"" + rs.getString(3) + "\",";
			html += "\"" + rs.getString(4) + "\");\n";
			funcID = topNO;
			funcTree.add(funcID);
			tn.getNodes().addElement(funcID);
			sumHtml = html + sumHtml;
		}
		tn.setContent(sumHtml);
		treePath.put(funcID, tn);
		return tn;
	}

	private HashSet hs = new HashSet();

	public String genSubject(Connection conn, String subjectNO)
			throws Exception {
		if (hs.contains(subjectNO))
			return "";
		
		hs.add(subjectNO);
		String sumHtml = "";
		Statement stmt = null;
 
		while (!subjectNO.equals(this.rootNO)) {
			stmt = conn.createStatement();
			String sql = "select TOPNO,SUBJECTNO,SUBJECTNAME from reportsubject where subjectNO='"
					+ subjectNO + "'";
			ResultSet rs = stmt.executeQuery(sql);
			if (!rs.next())
				return "_arrTreeView[ _arrTreeView.length ] = new Array('"
						+ this.rootNO + "','S" + subjectNO + "','其他報表能','');\n"
						+ sumHtml;

	 

			String html = "_arrTreeView[ _arrTreeView.length ] = new Array(";
			if (rs.getString(1).equals("$$$$$$$$")){
			   html += "\"" + this.rootNO + "\",";
			   subjectNO = this.rootNO;
			}else{
				html += "\"S" + rs.getString(1)+ "\",";
				subjectNO=rs.getString(1);
			}
			html += "\"S" + rs.getString(2) + "\",";
			html += "\"[" + rs.getString(3) + "]\",";
			html += "\"\");\n";
			 
			sumHtml = html + sumHtml;
		}
		return sumHtml;
	}

}
